import jwt
from fastapi import Depends, HTTPException, status, APIRouter, Request
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jwt import PyJWTError
from datetime import datetime, timedelta
from model.Token import Token
from model.Config import Config
router = APIRouter()

# SECRET_KEY = "09d25e094faa6ca2556c818166b7a95632b94f0ab4f05689d195e5142c95d9e3"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


def create_access_token(data: dict, expires_delta: timedelta = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, Config.instance.get_corpSecret(), algorithm=ALGORITHM)
    return encoded_jwt


async def get_current_user(token: str = Depends(oauth2_scheme)):
    print(token)
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, Config.instance.get_corpSecret(), algorithms=[ALGORITHM],
                             options={"verify_signature": True})
        username: str = payload.get("sub")
        if username is None:
            return False
        token_data = {"username": username}
    except PyJWTError:
        raise credentials_exception
    return token_data


@router.post("/login_for_access_token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    print(Config.instance.get_sEncodingAESKey())
    print(form_data.username, form_data.password)
    user = authenticate_user(form_data.username, form_data.password)
    print(user)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    print(access_token_expires)
    access_token = create_access_token(data={"sub": user}, expires_delta=access_token_expires)
    print(access_token)
    return {"access_token": access_token, "token_type": "bearer", "code": 200}


@router.post("/change_password")
async def change_password(request: Request):
    # 这里应该添加真实的用户验证逻辑
    # 例如，从数据库中查询用户名和密码是否匹配
    # 这里为了简单起见，我们假设用户名和密码都是 "user"
    query_params = await request.json()
    print(query_params.get("current-password"))
    print(query_params.get("new-password"))
    print(query_params.get("username"))
    if query_params.get("current-password") == Config.instance.get_password() and query_params.get("username") == Config.instance.get_user():
        Config.instance.set_password(query_params.get("new-password"))
        return {"msg": "ok", "code": 200}
    else:
        return {"msg": "err", "code": 500}


def authenticate_user(username: str, password: str):
    # 这里应该添加真实的用户验证逻辑
    # 例如，从数据库中查询用户名和密码是否匹配
    # 这里为了简单起见，我们假设用户名和密码都是 "user"
    if username == Config.instance.get_user() and password == Config.instance.get_password():
        return {"username": username}
    else:
        return None


@router.get("/users/me")
async def read_users_me(current_user: dict = Depends(get_current_user)):
    print("--------")
    return current_user


# 或者，你也可以为某个特定的路由添加一个依赖
@router.get("/items/")
async def read_items(current_user: dict = Depends(get_current_user)):
    return [{"item": "Foo"}, {"item": "Bar"}]
